let http = require('http')
let https = require('https')
let url = require('url')
const cheerio = require('cheerio')



const server = http.createServer()

server.on('request',(req,res)=>{
    const urlObj = url.parse(req.url,true)
    res.writeHead(200,{
        //键值对
        //跨域
        "content-type":"appliction/json;chartset=utf-8",
        "access-control-allow-origin":"*"//允许所有域
    })

    if(urlObj.pathname === '/api/getInfo'){
        //做和爬虫有关的事情
        //参数传一个匿名异步函数，用来做爬虫
        httpget(()=>{
            return res.end(spider(data))
        })

    }else{
        res.end('404')
    }
})

//https://i.maoyan.com/
function httpget(cb) {
    let data = ''
    https.get('https://i.maoyan.com/',()=>{
        res.on("data",(chunk)=>{
            data + chunk
        })//不断监听data的内容，拿到chunk数据片段

        res.on("end",()=>{//监听到最后，处理完数据
            cb(data)
        })
    })
}

//爬虫的函数
function spider(data){
    const $ = cheerio.load(data);
    let $movieList = $('.column.content')
    let movies = []
    $movieList.each((index,value)=>{
        movies.push({
            title:$(value).find('.title').text(),
            grade:$(value).find('.title').text(),
            actor:$(value).find('.actor').text(),
        })
    })
    console.log(movies)
    return JSON.stringify(movies)
}


server.listen(80,()=>{
    console.log('http://127.0.0.1')
})